package com.example.pei.ithinklearnt.utils;

import android.annotation.TargetApi;
import android.app.Activity;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;


public class PhotoUtil {
    /**
     * @param activity
     * @param uri          将要裁剪的文件的uri
     * @param file          裁剪文件的输出文件，应该new File(getExternalCacheDir(), "CoverImage" + currentUser.getMobilePhoneNumber() + ".jpg");这样的
     * @param aspectX       裁剪比例
     * @param aspectY
     * @param outputX       裁剪输出尺寸
     * @param outputY
     * @param requestCode
     *                      返回的是裁剪所得文件的uri
     */
    public static Uri cropImageUri(Activity activity,Fragment fragment, Uri uri, File file ,int aspectX,int aspectY,int outputX,int outputY, int requestCode){

        if(uri==null||file==null) return null;

        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri fileUri=updateUriFromFile(activity,file);

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.putExtra("scale", true);//黑边
        intent.putExtra("scaleUpIfNeeded", true);//黑边

        //设置输入图片格式
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("return-data", false);

        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        //是否关闭面部识别
        intent.putExtra("noFaceDetection", true); // no face detection
        //授权

        List<ResolveInfo> resInfoList = activity.getPackageManager()
                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        for (ResolveInfo resolveInfo : resInfoList) {
            String packageName = resolveInfo.activityInfo.packageName;
            activity.grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }

        if(fragment!=null){
            //启动
            fragment.startActivityForResult(intent, requestCode);
        }else{
            //启动
            activity.startActivityForResult(intent, requestCode);
        }
        return fileUri;
    }

    /**从路径获取到uri
     * @param context 上下文
     * @param path    文件路径
     * @return
     */
    public static Uri updateUriFromPath(Context context,String path) {
        Uri fileUri;
        if (Build.VERSION.SDK_INT < 24) {
            // 从文件中创建uri
            fileUri = Uri.fromFile(new File(path));
        } else {
            //兼容android7.0 使用共享文件的形式
//            ContentValues contentValues = new ContentValues(1);
//            contentValues.put(MediaStore.Images.Media.DATA, new File(path).getAbsolutePath());
//            fileUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            fileUri= FileProvider.getUriForFile(context,"com.example.pei.ithinklearnt.fileprovider",new File(path));
        }
        return fileUri;
    }

    /** 从文件获取到uri
     * @param context 上下文
     * @param file    文件
     * @return
     */
    public static Uri updateUriFromFile(Context context,File file) {
        Uri fileUri;
        if (Build.VERSION.SDK_INT < 24) {
            // 从文件中创建uri
            fileUri = Uri.fromFile(file);
        } else {
            //兼容android7.0 使用共享文件的形式
            fileUri= FileProvider.getUriForFile(context,"com.example.pei.ithinklearnt.fileprovider",file);
//            ContentValues contentValues = new ContentValues(1);
//            contentValues.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
//            fileUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        }
        return fileUri;
    }

    //对选取相册中的图片返回的Uri进行解析获得路径 兼容4.4以上和以下
    public static String getPathFromAlbum(Context context,Uri uri){
        if (uri == null) return null;
        //判断手机系统版本号
        if(Build.VERSION.SDK_INT>=19){
            //4.4及以上系统使用这个方法处理图片
            String imagePath = null;
            String a = uri.getAuthority();
            if (DocumentsContract.isDocumentUri(context, uri)) {
                //如果是documents类型的uri，则通过document id处理
                String docId = DocumentsContract.getDocumentId(uri);
                if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    String id = docId.split(":")[1];  //解析出数字格式的id
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(context,MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                            Long.valueOf(docId));
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                //如果是content类型的uri，则使用普通方式处理
                imagePath = getImagePath(context,uri, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                //如果是file类型的uri，直接获取图片路径即可
                imagePath = uri.getPath();
            }
            return imagePath;
        }else{
            //4.4及以下系统使用这个方法处理图片
            String imagePath = getImagePath(context,uri, null);
            return imagePath;
        }
    }



    public static String getImagePath(Context context,Uri uri,String selection){
        String path=null;
        //通过uri和selection来获取真实的图片路径
        Cursor cursor=context.getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if(cursor.moveToFirst()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }


    // 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,
    // 特点是:  File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变
    public static File compressBmpToFile(Bitmap bmp,File file){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 100;//个人喜欢从80开始,
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        options=90;
        while (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();
            if(options>20)
                options -= 5;
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    //压缩至Threshold 大小
    public static String compressImage(String filePath, String targetPath,int Threshold)  {
        Bitmap bm = getSmallBitmap(filePath);//获取一定尺寸的图片
        int degree = readPictureDegree(filePath);//获取相片拍摄角度
        if(degree!=0){//旋转照片角度，防止头像横着显示
            bm=rotateBitmap(bm,degree);
        }
        File outputFile=new File(targetPath);
        try {
            if (!outputFile.exists()) {
                outputFile.getParentFile().mkdirs();
                outputFile.createNewFile();
            }else{
                outputFile.delete();
            }
            //   FileOutputStream out = new FileOutputStream(outputFile);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int options = 100;//个人喜欢从80开始,
            bm.compress(Bitmap.CompressFormat.JPEG, options, baos);
            //     bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
            options=95;
            while (baos.toByteArray().length / 1024 > Threshold) {  //是否大于Threshold 兆
                baos.reset();
                if(options>20)
                    options -= 5;
                bm.compress(Bitmap.CompressFormat.JPEG, options, baos);
            }
            try {
                FileOutputStream fos = new FileOutputStream(outputFile);
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }catch (Exception e){}
        return outputFile.getPath();
    }
    /**
     * 根据路径获得图片信息并按比例压缩，返回bitmap
     */
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//只解析图片边沿，获取宽高
        BitmapFactory.decodeFile(filePath, options);
        // 计算缩放比
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        // 完整解析图片返回bitmap
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }
    /**
     * 获取照片角度
     * @param path
     * @return
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }
    /**
     * 旋转照片
     * @param bitmap
     * @param degress
     * @return
     */
    public static Bitmap rotateBitmap(Bitmap bitmap,int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress);
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
}
